#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <cerrno>
#include <cassert>
using namespace std;

int main(int argc,int argv){
    if(argc <= 2){
        cerr << "Usage: " << argv[0] << " <IP> <Port>" << endl;
        return 1;
    }
    const char* ip = argv[1];
    int port = atoi(argv[2]);

    struct sockaddr_in address;
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &address.sin_addr);
    address.sin_port = htons(port);

    int listenFd = socket(PF_INET, SOCK_STREAM, 0);
    assert(listenFd >= 0);

    int ret = bind(listenFd, (struct sockaddr*)&address, sizeof(address));
    assert(ret != -1);

    ret = listen(listenFd, 5);
    assert(ret != -1);

    struct sockaddr_in client;
    socklen_t clientLen = sizeof(client);
    int connFd = accept(listenFd, (struct sockaddr*)&client, &clientLen);
    if (connFd < 0) {
        cerr << "Error accepting connection: " << strerror(errno) << endl;
        close(listenFd);
    }

    char buf[1024];
    fd_set read_fds;
    fd_set exception_fds;
    FD_ZERO(&read_fds);
    FD_ZERO(&exception_fds);

    while(1){
        memset(buf, 0, sizeof(buf));

        FD_SET(connFd, &read_fds);
        FD_SET(connFd, &exception_fds);
        ret = select(connFd + 1, &read_fds, nullptr, &exception_fds, nullptr);
        if( ret < 0){
            cerr << "select failed : " << strerror(errno) << endl;
            break;
        }

        if(FD_ISSET(connFd, &read_fds)){
            ret = recv(connFd, buf, sizeof(buf) - 1, 0);
            if(ret < 0){
                cerr << "recv failed: " << strerror(errno) << endl;
                break;
            }
            cout << "get " << ret << " bytes of normal data: " << buf << endl;
        }
        else if (FD_ISSET(connFd, &exception_fds)){
            ret = recv(connFd, buf, sizeof(buf) - 1, MSG_OOB);
            if(ret < 0){
                cerr << "recv failed: " << strerror(errno) << endl;
                break;
            }
            cout << "get " << ret << " bytes of oob data: " << buf << endl;
        }
    }
    
    close(connFd); // 关闭连接
    close(listenFd);
    return 0;
}